package com.hmdp.utils;

import cn.hutool.core.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

@Component
public class RedisIdWorker {
    @Autowired
    private StringRedisTemplate redisTemplate;
    private static final long BEGIN_TIMESTAMP=1640995200L;
    private static final int COUNT_BITS=32;

    public long nextId(String keyPrefix){
        LocalDateTime now = LocalDateTime.now();
        long second = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = second - BEGIN_TIMESTAMP;

        String date = DateUtil.format(DateUtil.date(), "yyyyMMdd");
        Long count = redisTemplate.opsForValue().increment("icr" + keyPrefix + ":" + date);
        return timeStamp<<32 | count;
    }

}
